package com.itheima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.admin.feign.AdChannelFeign;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.service.ApiService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.wemedia.service.impl
 */
@Service
public class ApiServiceImpl implements ApiService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AdChannelFeign adChannelFeign;

    /**
     * 调用后台微服务，获取频道列表。
     * 优先使用redis缓存
     *
     * @return
     */
    @Override
    public List<AdChannel> getChannelList() {
        //1. 从redis获取
        String channelListJsonList = stringRedisTemplate.opsForValue().get(SystemConstants.REDISKEY_CHANNELLIST);
        List<AdChannel> channelList = null;
        if(StringUtils.isNotEmpty(channelListJsonList)) {
            //2. 有值，则转成List<AdChannel>对象
            channelList = JSON.parseArray(channelListJsonList, AdChannel.class);
        }
        //3. 如果redis中没值
        if(CollectionUtils.isEmpty(channelList)){
            //3.1 则远程调用admin微服务，查询所有频道列表
            ResultVo<List<AdChannel>> listResult = adChannelFeign.listAll();
            if(!listResult.isSuccess()){
                throw new LeadNewsException("调用后台查询频道列表失败!");
            }
            channelList = listResult.getData();
            //3.2 存入redis
            stringRedisTemplate.opsForValue().set(SystemConstants.REDISKEY_CHANNELLIST,JSON.toJSONString(channelList));
        }
        //4. 返回结果
        return channelList;
    }




}
